// auth.service.ts
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RegisterDto, LoginDto } from './auth.dto';
import { User } from 'src/entities/user.entity';
import { hashPassword, comparePassword } from '../utils/hash';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private jwtService: JwtService,
  ) {}

  async register(registerDto: RegisterDto) {
    const { username, password } = registerDto;
    const existingUser = await this.findUser(username);
    if (existingUser) {
      throw new HttpException(
        'Username already exists',
        HttpStatus.BAD_REQUEST,
      );
    }
    const hashedPassword = await hashPassword(password);
    const user = this.usersRepository.create({
      username,
      password: hashedPassword,
    });
    await this.usersRepository.save(user);
    return user;
  }

  async login(loginDto: LoginDto) {
    const { username, password } = loginDto;
    console.log(loginDto);
    const user = await this.usersRepository.findOne({ where: { username } });
    if (!user) {
      throw new HttpException(
        'Invalid username or password',
        HttpStatus.BAD_REQUEST,
      );
    }
    const isMatch = await comparePassword(password, user.password);
    if (!isMatch) {
      throw new HttpException(
        'Invalid username or password',
        HttpStatus.BAD_REQUEST,
      );
    }
    const payload = { username: user.username, id: user.id };
    console.log(this.jwtService);
    const token = this.jwtService.sign(payload); // 过期时间为1小时
    console.log(token);
    return { token };
  }

  async validateUser(payload: { username: string; id: number }): Promise<User> {
    const { username } = payload;
    console.log(payload);
    const user = await this.usersRepository.findOne({ where: { username } });
    console.log(user);
    if (!user) {
      throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
    }
    return user;
  }

  private async findUser(username: string): Promise<User> {
    return this.usersRepository.findOne({ where: { username } });
  }
}
